<template>
  <div class="container">
    <el-card>
      <div class="head">
        <div class="line"></div>
        <div class="title">电桩信息</div>
      </div>
      <hr>
      <div class="info">
        <el-row :gutter="20">
          <!-- 电桩编号 -->
          <el-col :span="6" class="elCol">
            <span>电桩编号</span>
            <div class="rightBox" @click="openDialog('equipmentCode')">
              <span>{{ formData.equipmentCode }}</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col>

          <!-- 电桩类型 -->
          <el-col :span="6" class="elCol">
            <span>电桩类型</span>
            <dict-tag :options="dict.type.charge_stake_equip_type" :value="formData.equipmentType"
              :show-overflow-tooltip="true" />
          </el-col>

          <!-- 供应厂商 -->
          <!-- <el-col :span="6" class="elCol">
            <span>供应厂商</span>
            <div class="rightBox" @click="openDialog('manufacturer')">
              <span>{{ formData.manufacturer }}</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col> -->

          <!-- 额定功率 -->
          <el-col :span="6" class="elCol">
            <span>额定功率</span>
            <div class="rightBox" @click="openDialog('power')">
              <span>{{ formData.power }}kw</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col>

          <!-- 所属站点 -->
          <el-col :span="6" class="elCol">
            <span>所属站点</span>
            <div class="rightBox" @click="openDialog('station')">
              <span>{{ formData.stationName }}</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col>

          <!-- 刷卡模式 -->
          <!-- <el-col :span="6" class="elCol">
            <span>刷卡模式</span>
            <div class="rightBox" @click="openDialog('cardMode')">
              <span>{{ formData.cardModeName }}</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col> -->

          <!-- 费率详情 -->
          <!-- <el-col :span="6" class="elCol">
            <span>费率详情</span>
            <div class="rightBox" @click="openDialog('rateDetail')">
              <span>{{ formData.rateDetail }}</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col> -->

          <!-- 预充电 -->
          <!-- <el-col :span="6" class="elCol">
            <span>预充电</span>
            <el-switch v-model="infoForm.preCharge" active-color="#13ce66"
              @change="handleSwitchChange('preCharge', $event)" inactive-color="#ff4949">
            </el-switch>
          </el-col> -->

          <!-- 当前费率 -->
          <!-- <el-col :span="6" class="elCol">
            <span>当前费率</span>
            <div class="rightBox">
              <span>查看</span>
              <i class="el-icon-view"></i>
            </div>
          </el-col> -->

          <!-- 定时充电 -->
          <!-- <el-col :span="6" class="elCol">
            <span>定时充电</span>
            <el-switch v-model="infoForm.scheduledCharging" active-color="#13ce66"
              @change="handleSwitchChange('scheduledCharging', $event)" inactive-color="#ff4949">
            </el-switch>
          </el-col> -->

          <!-- 桩自编号 -->
          <!-- <el-col :span="6" class="elCol">
            <span>桩自编号</span>
            <div class="rightBox" @click="openDialog('cardCode')">
              <span>设置</span>
              <i class="el-icon-edit-outline"></i>
            </div>
          </el-col> -->

          <!-- 当前温度 -->
          <!-- <el-col :span="6" class="elCol">
            <span>当前温度</span>
            <div class="rightBox">
              <span>查看</span>
              <i class="el-icon-view"></i>
            </div>
          </el-col> -->
        </el-row>
      </div>
    </el-card>

    <!-- 枪信息卡片 -->
    <el-card style="margin-top: 20px;">
      <div class="head">
        <div class="line"></div>
        <div class="title">枪信息</div>
      </div>
      <hr>
      <el-table v-loading="loading" class="qiangTable" :data="stakeList">
        <el-table-column label="枪序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="枪自编号" align="center" prop="gunAuto">
          <template slot-scope="scope">
            <div v-if="scope.row.gunAuto">
              {{ scope.row.gunAuto }}
            </div>
            <div v-else class="edit-box" @click="openDialog('gunAuto', scope.row.id)">
              <div class="tableHover">
                <span>未设置</span>
                <i class="el-icon-edit-outline"></i>
              </div>

            </div>

          </template>
        </el-table-column> -->


        <el-table-column label="额定功率/kw" align="center" prop="power" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" v-hasPermi="['business:stake:edit']">下发二维码</el-button>
            <el-button size="mini" type="text" v-hasPermi="['business:stake:edit']">下载二维码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 通用弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="form" :model="tempForm" label-width="120px" :rules="rules">
        <!-- 电桩编号 -->
        <el-form-item v-if="currentType === 'equipmentCode'" label="电桩编号" prop="equipmentCode">
          <el-input v-model="tempForm.equipmentCode" placeholder="请输入电桩编号"></el-input>
        </el-form-item>

        <!-- 供应厂商 -->
        <el-form-item v-if="currentType === 'manufacturer'" label="供应厂商" prop="manufacturer">
          <el-input v-model="tempForm.manufacturer" placeholder="请输入供应厂商" maxlength="20" show-word-limit></el-input>
        </el-form-item>

        <!-- 额定功率 -->
        <el-form-item v-if="currentType === 'power'" label="额定功率" prop="power">
          <el-input-number v-model="tempForm.power"></el-input-number>
        </el-form-item>

        <!-- 所属站点 -->
        <el-form-item v-if="currentType === 'station'" label="所属站点" prop="stationId">
          <el-select v-model="tempForm.stationId" placeholder="请选择所属站点" clearable>
            <el-option v-for="station in stationList" :key="station.value" :label="station.label"
              :value="station.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 刷卡模式 -->
        <el-form-item v-if="currentType === 'cardMode'" label="刷卡模式" prop="cardMode">
          <el-select v-model="tempForm.cardMode" placeholder="请选择刷卡模式" clearable>
            <el-option v-for="mode in cardModeList" :key="mode.value" :label="mode.label"
              :value="mode.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 桩自编号 -->
        <!-- <el-form-item v-if="currentType === 'cardCode'" label="桩自编号" prop="cardCode">
          <el-input v-model="tempForm.cardCode" placeholder="请输入桩自编号"></el-input>
        </el-form-item> -->
        <!-- 桩自编号 -->
        <el-form-item v-if="currentType === 'gunAuto'" label="枪自编号" prop="gunAuto">
          <el-input v-model="tempForm.gunAuto" placeholder="请输入枪自编号"></el-input>
        </el-form-item>
        <!-- 费率详情 -->
        <el-form-item v-if="currentType === 'rateDetail'" label="费率详情" prop="rateDetail">
          <el-input v-model="tempForm.rateDetail" placeholder="请输入费率详情"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listchargeStation } from "@/api/business/chargeStation";
import { getStake, updateStake } from "@/api/business/stake";
import { editGun } from "@/api/business/gun";

export default {
  dicts: ["charge_stake_equip_type"],
  data() {
    return {
      loading: false,
      // 上个页面带过来的id
      queryId: null,
      // 站点列表
      stationList: [],
      // 刷卡模式假数据
      cardModeList: [
        { value: 1, label: '本地结算模式' },
        { value: 2, label: '远程结算模式' },
        { value: 3, label: '混合结算模式' },
        { value: 4, label: '免密支付模式' }
      ],
      // 表单数据
      formData: {
        equipmentCode: 'zn434234',
        manufacturer: '合智数字能源',
        power: '120',
        cardCode: '123',
        gunAuto: '',
        stationId: '',
        stationName: '孝感市背景路',
        cardMode: 1,
        cardModeName: '本地结算模式',
        rateDetail: '2025服务费'
      },
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '',
      currentType: '',
      tempForm: {},
      // 表单验证规则
      rules: {
        equipmentCode: [{ required: true, message: '请输入电桩编号', trigger: 'blur' }],
        cardCode: [{ required: true, message: '请输入桩自编号', trigger: 'blur' }],
        gunAuto: [{ required: true, message: '请输入枪自编号', trigger: 'blur' }],
        manufacturer: [{ required: true, message: '请输入供应厂商', trigger: 'blur' }],
        power: [{ required: true, message: '请输入额定功率', trigger: 'blur' }],
        stationId: [{ required: true, message: '请选择所属站点', trigger: 'change' }],
        cardMode: [{ required: true, message: '请选择刷卡模式', trigger: 'change' }],
        rateDetail: [{ required: true, message: '请输入费率详情', trigger: 'blur' }]
      },
      // 开关相关
      infoForm: {
        preCharge: true,
        scheduledCharging: true,
      },
      tempSwitch: {
        preCharge: true,
        scheduledCharging: true,
      },
      // 枪信息列表
      stakeList: [
      ],
      gunId: null
    };
  },
  created() {
    this.queryId = this.$route.query.equipmentId
    this.getStakeInfo()
    this.getListchargeStation();

  },
  methods: {
    getStakeInfo() {
      getStake(this.queryId).then((response) => {
        console.log(response, 'response')
        this.stakeList = response.data.chargeConnectorList
        this.formData = response.data
        // this.formData.equipmentType = response.data.equipmentType
        // this.formData.power = response.data.power
        // this.formData.equipmentCode = response.data.equipmentCode
      })
    },
    getListchargeStation() {
      listchargeStation().then((response) => {
        this.stationList = response.rows.map((item) => {
          return {
            value: item.stationId,
            label: item.stationName,
          };
        });
        // 增加判断，避免obj为undefined
        const obj = this.stationList.find((item) => item.value == this.formData.stationId);
        this.formData.stationName = obj ? obj.label : '';
        // 如果有站点数据，设置默认值
        if (this.stationList.length > 0 && !this.formData.stationId) {
          const defaultStation = this.stationList.find(s => s.label === this.formData.stationName);
          if (defaultStation) {
            this.formData.stationId = defaultStation.value;
          }
        }
      });
    },

    // 打开弹窗
    openDialog(type, id) {
      this.gunId = id
      this.currentType = type;
      // 设置弹窗标题
      const titleMap = {
        equipmentCode: '编辑电桩编号',
        cardCode: '编辑桩自编号',
        manufacturer: '编辑供应厂商',
        power: '编辑额定功率',
        station: '编辑所属站点',
        cardMode: '编辑刷卡模式',
        rateDetail: '编辑费率详情',
        gunAuto: '编辑枪自编号',
      };
      this.dialogTitle = titleMap[type];

      // 初始化临时表单数据
      this.tempForm = { ...this.formData };

      // 显示弹窗
      this.dialogVisible = true;
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 更新表单数据
          this.formData = { ...this.tempForm };
          // 特殊处理：如果需要在显示时带单位，可在这里处理
          // （根据实际需求决定是否保留）
          // if (this.currentType === 'power') {
          //   this.formData.powerDisplay = `${this.tempForm.power}kw`;
          // }

          // 特殊处理显示值
          if (this.currentType === 'station') {
            const selected = this.stationList.find(s => s.value === this.tempForm.stationId);
            this.formData.stationName = selected ? selected.label : '';
          }

          if (this.currentType === 'cardMode') {
            const selected = this.cardModeList.find(m => m.value === this.tempForm.cardMode);
            this.formData.cardModeName = selected ? selected.label : '';
          }
          if (this.dialogTitle == '编辑枪自编号') {
            editGun({ id: this.gunId, gunAuto: this.tempForm.gunAuto }).then((response) => {
              this.getStakeInfo()
              this.$message.success('修改成功');
              this.dialogVisible = false;
            })
          } else {
            updateStake(this.formData).then((response) => {
              this.$message.success('修改成功');
              this.dialogVisible = false;
            })
          }



        }
      });
    },

    // 开关切换处理
    handleSwitchChange(key, val) {
      this.tempSwitch[key] = !val;
      this.$confirm(
        `确认要${val ? '开启' : '关闭'}${this.getSwitchName(key)}?`,
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.infoForm[key] = val;
        })
        .catch(() => {
          this.infoForm[key] = this.tempSwitch[key];
        });
    },

    // 获取开关名称
    getSwitchName(key) {
      const nameMap = {
        preCharge: '预充电',
        scheduledCharging: '定时充电'
      };
      return nameMap[key] || key;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 0;
}

.container {
  padding: 20px;

  hr {
    border: none;
    border-top: 1px solid #eee;
    margin: 10px 0;
  }

  .head {
    display: flex;
    padding: 15px 20px;

    .line {
      width: 5px;
      background: blue;
    }

    .title {
      margin-left: 10px;
      font-weight: 600;
    }
  }

  .info {
    padding: 20px;

    .elCol {
      display: flex;
      align-items: center;
      height: 40px;
      box-sizing: border-box;

      >span:first-child {
        width: 80px;
        color: #606266;
      }

      .rightBox {
        display: flex;
        align-items: center;
        padding-bottom: 2px;
        margin-top: 2px;
        cursor: pointer;
        transition: all 0.2s;
        margin-left: 10px;

        &:hover {
          border-bottom: 1px solid #409eff;
          color: #409eff;

          .el-icon {
            color: #409eff;
          }
        }

        span {
          margin-right: 10px;
          transition: color 0.2s;
        }

        .el-icon {
          transition: color 0.2s;
          color: #c0c4cc;
        }
      }
    }
  }

  .qiangTable {
    padding: 20px;

    .edit-box {
      display: flex;
      justify-content: center;
      align-items: center;

      .tableHover {
        width: 80px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          border-bottom: 1px solid #409eff;
          color: #409eff;

          .el-icon {
            color: #409eff;
          }
        }

        span {
          margin-right: 10px;
          transition: color 0.2s;
        }

        .el-icon {
          transition: color 0.2s;
          color: #c0c4cc;
        }
      }

    }
  }
}
</style>
